package com.gjs.freechat.web.business;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gjs.freechat.server.business.UserManageBusiness;
import com.gjs.freechat.server.component.bean.UserInfo;
import com.gjs.freechat.server.dao.UserDao;
import com.gjs.freechat.utils.SHA1;
import com.gjs.freechat.web.constant.WebConstants;
import com.gjs.freechat.web.utils.MyWebUtils;

@Service
public class WebUserManage {
	
	private static Logger logger = Logger.getLogger(WebUserManage.class);
	
	@Autowired
	UserManageBusiness userManageBusiness;
	
	@Autowired
	UserDao userDao;
	
	/**
	 * 已注册登录方式
	 * @param email
	 * @param password
	 * @param request
	 * @param response
	 * @return
	 */
	public int registeredLogin(String email, String password, 
			HttpServletRequest request, HttpServletResponse response) {
		password = SHA1.encode(password);
		Map<String, Object> result = userManageBusiness.login(email, password);
		if (result.get("userInfo") != null) {
			UserInfo userInfo = (UserInfo)result.get("userInfo");
			webLoginRegister(userInfo, request.getSession()); 
			saveUserToCookie(response, userInfo.getUserName(), password);
		}
		int resultCode = (Integer) result.get("resultCode");
		return resultCode;
	}
	
	/**
	 * 未注册登录方式
	 * @param request
	 * @param response
	 * @return
	 */
	public int unregisterLogin(HttpServletRequest request, HttpServletResponse response) {
		UserInfo userInfo = getUserByCookie(request, response);
		if (userInfo == null) {
			userInfo = userManageBusiness.createNewUser();
			saveUserToCookie(response, userInfo.getUserName(), userInfo.getPassword());
			//userInfo.setPassword(null);
		}
		webLoginRegister(userInfo, request.getSession());
		userManageBusiness.loginRegister(userInfo);
		return WebConstants.LOGIN_RESULT_SUCCESS;
	}
	
	public int logout(HttpServletRequest request, HttpServletResponse response) {
		UserInfo userInfo = (UserInfo) MyWebUtils.getHttpSessionAttr(request, "userInfo");
		if (userInfo == null) {
			return WebConstants.LOGOUT_SUCCESS;
		}
		webLogoutRegister(request.getSession());
		userManageBusiness.logout(userInfo);
		return WebConstants.LOGOUT_SUCCESS;
	}
	
	/**
	 * 通过获取到客户端保存的用户名和密码来获取用户信息
	 * @param request
	 * @param response
	 * @return
	 */
	public UserInfo getUserByCookie(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		String username = null, password = null;
		for (int i = 0; i < cookies.length; i++) {
			if ("fcUsername".equals(cookies[i].getName())) {
				username = cookies[i].getValue();
			}
			if ("fcPassword".equals(cookies[i].getName())) {
				password = cookies[i].getValue();
			}
		}
		if (username != null) {
			return userDao.getUserInfo(username, password);
		}
		return null;
	}
	
	/**
	 * 将用户信息存入应用程序的session中
	 * @param userInfo
	 * @param session
	 */
	public void webLoginRegister(UserInfo userInfo, HttpSession session) {
		//Authorization authorization = new Authorization(userInfo);
		//session.setAttribute("authorization", authorization);
		
		session.setAttribute("userInfo", userInfo);
	}
	
	public void webLogoutRegister(HttpSession session) {
		session.invalidate();
	}
	
	public static String COOKIE_USERNAME = "fcUsername";
	public static String COOKIE_PASSWORD = "fcPassword";
	
	/**
	 * 将用户名和密码通过cookie的方式存入浏览器端
	 * @param response
	 * @param name
	 * @param psw
	 */
	public void saveUserToCookie(HttpServletResponse response, String name, String psw) {
		Cookie username = new Cookie(COOKIE_USERNAME, name);
		Cookie password = new Cookie(COOKIE_PASSWORD, psw);
		Cookie loginWay = new Cookie("loginWay", WebConstants.LOGIN_WAY_AUTO + "");
		int age = 60 * 60 * 24 * 10;
		username.setMaxAge(age);
		password.setMaxAge(age);
		loginWay.setMaxAge(age);
		loginWay.setPath(MyWebUtils.getContextPath());
		
		response.addCookie(username);
		response.addCookie(password);
		response.addCookie(loginWay);
	}
	
	public void removeUserCookie(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		int age = 60 * 60 * 24 * 10;
		for (int i = 0; i < cookies.length; i++) {
			if ("loginWay".equals(cookies[i].getName())) {
				cookies[i].setMaxAge(age);
				cookies[i].setValue(WebConstants.LOGIN_WAY_MANUAL + "");
				cookies[i].setPath(MyWebUtils.getContextPath());
			} else {
				cookies[i].setMaxAge(0);
			}
			response.addCookie(cookies[i]);
		}
	}
	
	
	public UserInfo getLoginedUserInfo(HttpServletRequest request) {
		return (UserInfo) MyWebUtils.getHttpSessionAttr(request, "userInfo");
	}
	
	public void updateUserInfo(UserInfo newUserInfo, HttpServletRequest request) {
		UserInfo old = getLoginedUserInfo(request);
		old.updateBasicInfo(newUserInfo);
	}
	
	public void updateCookie(String value, String cookieName, HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		int age = 60 * 60 * 24 * 10;
		for (int i = 0; i < cookies.length; i++) {
			if (cookies[i].getName().equals(cookieName)) {
				cookies[i].setValue(value);
			}
			//cookies[i].setMaxAge(age);
			response.addCookie(cookies[i]);
		}
	}
	
}
